package org.microframework.cloud.system.service.impl;

import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;

import org.microframework.cloud.system.service.LoginLogService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

/**
 * 登录日志服务实现类
 * 等保要求：异步记录登录日志，不影响主流程性能
 */
@Slf4j
@Service
public class LoginLogServiceImpl implements LoginLogService {

    /**
     * 记录登录成功日志
     * 等保要求：记录用户登录成功的详细信息
     */
    @Async
    @Override
    public void recordLoginSuccess(String username, HttpServletRequest request) {
        CompletableFuture.runAsync(() -> {
            try {
                // 获取请求信息
                String ip = getIpAddress(request);
                String userAgent = request.getHeader("User-Agent");
                LocalDateTime loginTime = LocalDateTime.now();
                
                // TODO: 实际项目中应将日志保存到数据库
                log.info("登录成功日志 - 用户名: {}, IP: {}, 时间: {}, 设备: {}", 
                        username, ip, loginTime, userAgent);
                
                // 记录敏感操作日志，等保要求
                log.info("敏感操作日志 - 类型: 用户登录, 结果: 成功, 用户名: {}, IP: {}, 时间: {}", 
                        username, ip, loginTime);
            } catch (Exception e) {
                log.error("记录登录成功日志失败", e);
            }
        });
    }

    /**
     * 记录登录失败日志
     * 等保要求：记录用户登录失败的详细信息和原因
     */
    @Async
    @Override
    public void recordLoginFailure(String username, String failReason, HttpServletRequest request) {
        CompletableFuture.runAsync(() -> {
            try {
                // 获取请求信息
                String ip = getIpAddress(request);
                String userAgent = request.getHeader("User-Agent");
                LocalDateTime loginTime = LocalDateTime.now();
                
                // TODO: 实际项目中应将日志保存到数据库
                log.warn("登录失败日志 - 用户名: {}, 原因: {}, IP: {}, 时间: {}, 设备: {}", 
                        username, failReason, ip, loginTime, userAgent);
                
                // 记录敏感操作日志，等保要求
                log.warn("敏感操作日志 - 类型: 用户登录, 结果: 失败, 原因: {}, 用户名: {}, IP: {}, 时间: {}", 
                        failReason, username, ip, loginTime);
                
                // TODO: 检测连续登录失败，实现账号锁定策略
            } catch (Exception e) {
                log.error("记录登录失败日志失败", e);
            }
        });
    }
    
    /**
     * 获取请求IP地址
     * 
     * @param request HTTP请求
     * @return IP地址
     */
    private String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
} 